//
//  LHStatuseAboutViewModel.swift
//  LHWeiBo
//
//  Created by snowimba on 16/1/22.
//  Copyright © 2016年 snowimba. All rights reserved.
//

import UIKit
import AFNetworking

class LHStatuseAboutViewModel: NSObject {

	var statusesArr: [LHStatuseCellViewModel]?

	static let sharedStatusVM : LHStatuseAboutViewModel = LHStatuseAboutViewModel()

	func loadStatusData(finishBlack: (isSucced: Bool) -> ()) {
//        https://api.weibo.com/2/statuses/friends_timeline.json
		let since_id = statusesArr?.first?.status?.id ?? 0
		let URLString = "https://api.weibo.com/2/statuses/friends_timeline.json?access_token=\(LHLoginAboutViewModel.sharedViewModel.userInfo!.access_token!)&since_id=\(since_id)&max_id=0"
//        URLString	String	"https://api.weibo.com/2/statuses/friends_timeline.json?access_token=Optional(\"2.00eqen3GYIasLEb0107eba1cdreenC\")"
		LHSessionManager.sessionManager.request(URLString: URLString, parameters: nil) { (response, error) -> () in

			if error != nil {

				print(error)

				finishBlack(isSucced: false)
				return
			}

			3
			let dict : [String: AnyObject] = response! as! [String: AnyObject]

//            print(dict)

			let arr = dict["statuses"] as! [[String: AnyObject]]

//            self.statusesArr?.removeAll()
			var temArrM = [LHStatuseCellViewModel]()
			for dictA in arr {
				let status = LHStatusM(dict: dictA)
				temArrM.append(LHStatuseCellViewModel(statuses: status))
			}
			if self.statusesArr == nil {

				self.statusesArr = [LHStatuseCellViewModel]()
			}
			self.statusesArr = temArrM + self.statusesArr!

			finishBlack(isSucced: true)
		}
	}

	func loadMoreStatusData(finishBlack: (isSucced: Bool) -> ()) {

		// https://api.weibo.com/2/statuses/friends_timeline.json
		var max_id = statusesArr?.last?.status?.id ?? 0

		if max_id != 0 {

			max_id -= 1
		}
		let URLString = "https://api.weibo.com/2/statuses/friends_timeline.json?access_token=\(LHLoginAboutViewModel.sharedViewModel.userInfo!.access_token!)&since_id=0&max_id=\(max_id)"
		// URLString	String	"https://api.weibo.com/2/statuses/friends_timeline.json?access_token=Optional(\"2.00eqen3GYIasLEb0107eba1cdreenC\")"
		LHSessionManager.sessionManager.request(URLString: URLString, parameters: nil) { (response, error) -> () in

			if error != nil {

				print(error)

				finishBlack(isSucced: false)
				return
			}

			3
			let dict : [String: AnyObject] = response! as! [String: AnyObject]

			// print(dict)

			let arr = dict["statuses"] as! [[String: AnyObject]]

			var temArrM = [LHStatuseCellViewModel]()

			for dictA in arr {

				let status = LHStatusM(dict: dictA)

				temArrM.append(LHStatuseCellViewModel(statuses: status))
			}

			self.statusesArr! += temArrM
//			self.statusesArr = temArrM

			finishBlack(isSucced: true)
		}
	}
}
